package bTree.LeetCode;

import java.util.HashMap;

public class 单词规律 {
    public boolean wordPattern(String pattern, String s) {
        int left = 0;
        int right = 0;
        int index = 0;
        String[] ss = new String[10000];
        if(s.length()==1){
            ss[0]=s;
            index=1;
        }
        while (right != s.length() - 1) {
            while (right != s.length() - 1&&s.charAt(right + 1) != ' '  ) {
                right++;
            }
            ss[index] = s.substring(left, right + 1);
            index++;
            if (right == s.length() - 1) {
                break;
            }
            left = right + 2;
            right = right + 2;
            if(right==s.length()-1){
                ss[index] = s.substring(left, right + 1);
                index++;
            }
        }
        if(index!=pattern.length()){
            return false;
        }
        HashMap<Character,String>hashMap=new HashMap<>();
        for (int i = 0; i < index; i++) {
            if(!hashMap.containsKey(pattern.charAt(i))){
                if(hashMap.containsValue(ss[i])){
                    return false;
                }
                hashMap.put(pattern.charAt(i),ss[i]);
            }else {
                if(!hashMap.get(pattern.charAt(i)).equals(ss[i])){
                    return false;
                }
            }
        }
        return true;
    }
}
